const userService = require('./../services/users.service');
const email = require('../utils/email');
const fs = require('fs');
const path = require('path');
module.exports = {
    /**
     * 注册
     * @param 
     */
    async register(ctx) {
        let formData = ctx.request.body;
        let result = {
            result: false,
            message: ''
        };
        // 校验表单信息格式
        let res_form_validator = userService.validatorRegister(ctx, formData);
        if (!res_form_validator.result) {
            ctx.body = res_form_validator;
            return
        };
        // 校验验证码
        let res = formData.idCode == ctx.session.idCode;
        console.log(ctx);
        if (!res) {
            result.message = '验证码错误';
            ctx.body = result;
            return;
        }
        // 数据库 检测邮箱
        if (await userService.isExist(formData)) {
            result.message = '邮箱已注册';
            ctx.body = result;
            return
        }
        //插入数据库
        let userResult = await userService.insertInfo(formData);
        if (userResult && userResult.affectedRows) {
            result.message = '注册成功';
            result.result = true;
            // ctx.session = null;
        } else {
            result.message = '注册失败';
        };
        ctx.body = result;
    },
    /**
     * 登录
     */
    async signIn(ctx) {
        let result = {
            result: false,
            message: '用户名或密码错误'
        };
        let email = ctx.query.email;
        let passwordEncrypt = ctx.query.passwordEncrypt;
        // 检验
        let res = await userService.signIn({ email, passwordEncrypt });
        if (res) {
            result.result = true;
            result.message = '登录成功';
            result.user_id = res.user_id;
            ctx.session.isLogin = true;
            ctx.session.user_id = res.user_id;
            ctx.body = result;
            return;
        }
        ctx.body = result;
    },
    /**
     * 登出
     */
    async logOut(ctx) {
        let result = {
            result: false,
            message: '您还未登录'
        };

        if (ctx.session.isLogin) {
            let formData = ctx.request.body;
            if (formData.logout) {
                // 清空session
                ctx.session = null;
                // 修改返回信息
                result.result = true;
                result.message = '登出成功';
            } else {
                result.message = '字段格式不正确';
            }
        };
        ctx.body = result;
    },

    /**
     * 获取用户信誉评价 单一值
     * */
    async credit_single(ctx) {
        let result = {
            result: false,
            message: '',
        };
        let scoreer = ctx.query.scoreer;
        let owner = ctx.query.owner;
        let res = await userService.getCreditSingle({
            scoreer,
            owner
        });
        if (res) {
            result.result = true;
            result.score = res.score;
        } else {
            result.message = '暂无评价';
        }
        ctx.body = result;
    },
    /**
     * 获取用户信誉积分 平均值
     */
    async credit_average(ctx) {
        let result = {
            result: false,
            message: '',
        };
        let session = ctx.session;
        let user_id = ctx.query.user_id || session.user_id || false;
        if (user_id) {
            let res = await userService.getCreditAverage({
                user_id
            });
            let key = 'AVG(score)';
            result.result = true;
            result.score = res[key] ? Math.floor(res[key]) : 5;
        } else {
            ctx.message = '请输入用户ID';
        }
        ctx.body = result;
    },
    /**
     *  获取用户个人信息
     * 
     */
    async getInfo(ctx) {
        let res = {
            result: false,
            message: ''
        };
        let user_id = ctx.query.user_id || ctx.session.user_id || false;
        if (user_id) {
            // 获取指定用户信息
            let res_info = await userService.getInfoById({
                user_id
            });
            console.log(res_info)
            if (res_info) {
                res.result = true;
                res.nickname = res_info.nickname;
                res.email = res_info.email;
                res.picture_name = res_info.picture_name === '' ? '' : '/portrait/' + res_info.picture_name;
                res.major = res_info.major;
                res.grade = res_info.grade;
                res.campus = res_info.campus;
                res.phone = res_info.phone;
            } else {
                res.message = '用户不存在';
            }
        } else {
            res.message = '请输入用户ID';
        }
        ctx.body = res;
    },

    /**
     *  修改用户个人信息
     * 
     */
    async modifyInfo(ctx) {
        let res = {
            result: false,
            message: ''
        };
        let user_id = ctx.session.user_id || false;
        let formData = ctx.request.body;
        if (user_id) {
            // 修改指定用户信息
            let res_info = await userService.modifyInfo({
                user_id,
                data: {
                    ...formData
                }
            });
            if (res_info && res_info.affectedRows) {
                res.result = true;
                res.message = '修改成功';
            } else {
                res.message = '修改失败';
            }
        } else {
            res.message = '请先登录';
        }
        ctx.body = res;
    },

    /**
     * 上传用户头像
     */
    async upload_portrait(ctx) {
        let result = {
            result: false,
            message: '上传失败'
        };
        if (ctx.session.isLogin) {
            let user_id = ctx.session.user_id;
            // 获取上传文件
            const file = ctx.request.files.image;
            // 创建可读流
            const reader = fs.createReadStream(file.path);
            const ext = file.name.split('.').pop();
            // 文件名
            let fileName = `${Date.now().toString()}.${ext}`;
            let filePath = path.join(__dirname, '../public/portrait/') + fileName;
            const upStream = fs.createWriteStream(filePath);
            reader.pipe(upStream);
            // 写入数据库
            let res = await userService.upload_portrait({
                fileName,
                user_id
            });
            if (res && res.affectedRows) {
                result.result = true;
                result.message = '上传成功';
            }
        } else {
            result.message = '请先登录';
        }

        ctx.body = result;
    },
    /**
     *发送验证码
     */
    async sendIdCode(ctx) {
        let result = {
            result: false,
            message: '发送失败',
        };
        let idCode = Math.floor(Math.random() * (9000)) + 1000;
        ctx.session.idCode = idCode;
        let emailTo = ctx.query.emailTo;
        if (emailTo) {
            let res = await email.sendIdCode(emailTo, idCode);
            if (res && res.messageId) {
                result.result = true;
                result.message = '发送成功';
                result.idCode = idCode;
            }
        } else {
            result.message = '请输入邮箱';
        }
        ctx.body = result;
    },
    /**
     * 添加用户收藏
     */
    async addCollect(ctx) {
        let result = {
            result: false,
            message: '',
        };
        let formData = ctx.request.body;
        let user_id = ctx.session.user_id || false;
        if (user_id) {
            let res = await userService.addCollect({
                user_id,
                book_id: formData.book_id
            });
            if (res && res.affectedRows) {
                result.result = true;
                result.message = '收藏成功';
            } else {
                result.message = '已收藏';
            }
        } else {
            result.message = '请先登录';
        }
        ctx.body = result;
    },
    /**
     * 查看用户收藏
     */
    async collect(ctx) {
        let result = {
            result: false,
            message: '',
        };
        let user_id = ctx.session.user_id || false;
        if (user_id) {
            let res = await userService.collect({
                user_id
            });
            result.result = true;
            result.book_info = res;
        } else {
            result.message = '请先登录';
        }
        ctx.body = result;
    },
    /**
     * 取消收藏
     */
    async removeCollect(ctx) {
        let result = {
            result: false,
            message: '取消收藏失败'
        };
        let user_id = ctx.session.user_id || false;
        if (user_id) {
            let res = await userService.removeCollect({
                id: ctx.query.id
            });
            if (res && res.affectedRows) {
                result.result = true;
                result.message = '取消收藏成功';
            }
        } else {
            result.message = '请先登录';
        }
        ctx.body = result;
    }
}